package com.t.util;

//import com.google.gson.Gson;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;


import javax.swing.*;
import java.awt.*;
import java.io.IOException;
@Component
public class QiniuCloud {
    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "dB3dIncPcvEoQ_Pi-vq05goXJ74yV1Xrfkx8UBLQ";
    private static final String SECRET_KEY = "q6rV9e76JnQbIE0ndTDZQxPisFaNAUgPKHDQyKEe";
    // 要上传的空间
    private static final String bucketname = "drugsource";
    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static final String DOMAIN = "qiniu.fengping.xyz";

    private static final String style = "imageView2/2/w/200/h/200/q/75";
    public String getUpToken() {
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
    }
    // 普通上传
    public String upload(String filePath, String UpfileName) throws IOException {
        Zone zone = Zone.zoneAs0();
        Configuration cfg = new Configuration(zone);
        // 创建上传对象
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            // 调用put方法上传
            String token = auth.uploadToken(bucketname);
            if(token.isEmpty()) {
                System.out.println("未获取到token，请重试！");
                return null;
            }
            Response res = uploadManager.put(filePath, UpfileName, token);
            // 打印返回的信息
            System.out.println(res.bodyString());
            if (res.isOK()) {
                Ret ret = res.jsonToObject(Ret.class);
                //如果不需要对图片进行样式处理，则使用以下方式即可
                //return DOMAIN + ret.key;
//            返回实例：    http://qx5nmyi15.hn-bkt.clouddn.com/test.jpg
                return "http://"+DOMAIN +"/"+ ret.key;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }
        return null;
    }

    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }
}
